package com.example.demo.controller;

import com.example.demo.model.College;
import com.example.demo.service.CollegeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/colleges")
@CrossOrigin(origins = "http://localhost:5173") // 允许前端访问
public class CollegeController {
    @Autowired
    private CollegeService collegeService;

    // 获取所有学院（支持分页和搜索）
    @GetMapping
    public Page<College> getAllColleges(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String status) {
        
        // 如果提供了搜索条件，则执行搜索
        if ((name != null && !name.isEmpty()) || (status != null && !status.isEmpty())) {
            College.Status statusEnum = null;
            if (status != null && !status.isEmpty()) {
                try {
                    statusEnum = College.Status.valueOf(status);
                } catch (IllegalArgumentException e) {
                    // 如果状态值无效，则忽略状态搜索条件
                }
            }
            return collegeService.searchColleges(name, statusEnum, page, size);
        } else {
            // 否则返回所有学院
            return collegeService.getAllColleges(page, size);
        }
    }

    // 根据ID获取学院
    @GetMapping("/{id}")
    public ResponseEntity<College> getCollegeById(@PathVariable Long id) {
        Optional<College> college = collegeService.getCollegeById(id);
        if (college.isPresent()) {
            return ResponseEntity.ok(college.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 创建学院
    @PostMapping
    public College createCollege(@RequestBody College college) {
        return collegeService.saveCollege(college);
    }

    // 更新学院
    @PutMapping("/{id}")
    public ResponseEntity<College> updateCollege(@PathVariable Long id, @RequestBody College collegeDetails) {
        Optional<College> college = collegeService.getCollegeById(id);
        if (college.isPresent()) {
            College updatedCollege = college.get();
            updatedCollege.setName(collegeDetails.getName());
            updatedCollege.setCode(collegeDetails.getCode());
            updatedCollege.setDescription(collegeDetails.getDescription());
            updatedCollege.setStatus(collegeDetails.getStatus());
            collegeService.saveCollege(updatedCollege);
            return ResponseEntity.ok(updatedCollege);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 删除学院
    @DeleteMapping("/{id}")
    public ResponseEntity<String> deleteCollege(@PathVariable Long id) {
        Optional<College> college = collegeService.getCollegeById(id);
        if (college.isPresent()) {
            // 检查学院是否有关联的专业
            if (collegeService.hasMajors(id)) {
                return ResponseEntity.badRequest().body("无法删除学院，该学院下有关联的专业数据");
            }
            
            collegeService.deleteCollege(id);
            return ResponseEntity.ok("学院删除成功");
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据代码获取学院
    @GetMapping("/code/{code}")
    public ResponseEntity<College> getCollegeByCode(@PathVariable String code) {
        Optional<College> college = collegeService.getCollegeByCode(code);
        if (college.isPresent()) {
            return ResponseEntity.ok(college.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // 根据名称搜索学院
    @GetMapping("/search")
    public List<College> searchCollegesByName(@RequestParam String name) {
        return collegeService.getCollegesByName(name);
    }
}